package com.showmaker.controller;

import com.alibaba.fastjson.JSON;
import com.showmaker.bean.Member;
import com.showmaker.constant.MessageConstant;
import com.showmaker.constant.RedisConstant;
import com.showmaker.constant.RedisMessageConstant;
import com.showmaker.entity.Result;
import com.showmaker.service.MemberService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 会员相关的业务
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference(interfaceClass = MemberService.class, version = "1.0")
    private MemberService memberService;

    /**
     * 通过验证码进行登录
     * @param map 封装手机号和验证码
     * @return 返回登录的结果（成功 / 失败）
     */
    @RequestMapping("/login")
    public Result login(@RequestBody Map<String, Object> map, HttpServletResponse response) {
        // 1.验证输入的验证码是否正确，如果验证码错误则登录失败
        // 1-1 从请求中获取手机号和验证码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        // 1-2 从 Redis 中获取验证码
        String validateCodeInRedis = redisTemplate.opsForValue().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        // 1-3 比较验证码
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            // 如果二者是相等的，说明输入的验证码正确，进行登录处理
            // 2.判断当前用户是否是会员，如果不是会员，则完成自动会员注册
            // 2-1 通过手机号查询当前用户是否已经注册
            Member member = memberService.getMemberByTelephone(telephone);
            // 2-2 如果没有注册的用户，帮其完成自动注册
            if (member == null) {
                member = new Member();
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.insertMember(member);
            }

            // 3.向客户端写入Cookie，内容为用户手机号
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(cookie);

            // 4.将会员信息保存到 Redis 中
            String json = JSON.toJSON(member).toString();
            redisTemplate.opsForValue().set(telephone, json, 30, TimeUnit.MINUTES);

            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            // 如果输入的验证码错误，直接返回登录失败的信息
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
